<template>
  <el-dialog :visible.sync="userVisible" :title="title" width="50%"  :close-on-click-modal="false">
    <el-form ref="rel" :model="ruleForm" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <!-- 第一行：用户姓名 -->
        <el-col :span="8">
          <el-form-item label="用户姓名:" prop="UserName">
            <el-select v-model="ruleForm.UserName" placeholder="请选择用户"  :disabled="!ruleFormQX.UserName" clearable filterable @change="handleUserChange"
              style="width: 100%">
              <el-option v-for="user in userinfo" :key="user.ROWID" :label="user.UserName" :value="user.ROWID" />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 第一行：用户岗位类型 -->
        <el-col :span="10">
          <el-form-item label="用户岗位类型:" prop="JobType" style="text-align: left;">
            <el-radio-group v-model="ruleForm.JobType" :disabled="!ruleFormQX.JobType">
              <el-radio :label="0">主职</el-radio>
              <el-radio :label="1">兼职</el-radio>
              <el-radio :label="2">借调</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- 第一行：主持工作 -->
        <el-col :span="6">
          <el-form-item label="主持工作:" prop="IsWork" style="text-align: left;">
            <el-checkbox v-model="ruleForm.IsWork" :disabled="!ruleFormQX.IsWork" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：工作职责（整行） -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工作职责:" prop="JobRespon">
            <el-input v-model="ruleForm.JobRespon" type="textarea" :rows="3" placeholder="请输入工作职责"  :disabled="!ruleFormQX.JobRespon"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：备注（整行） -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注:" prop="Memo">
            <el-input v-model="ruleForm.Memo" type="textarea" :rows="3" placeholder="请输入备注信息"  :disabled="!ruleFormQX.Memo"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行：按钮 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item style="text-align: right;">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancelForm">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { GetData, BatchTableOperateRequestByCRUD } from '@/api/Hr';
export default {
  props: {
    userVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    userdj: {
      type: Array,
      default: () =>  [] 
    },
    depjobrow:{
       type: Object,
      default: () => ({})
    },
    userlist: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
       ruleForm: {
        UserName: '',      // 初始化所有字段
        ROWID: '',         // 新增ROWID字段
        JobType: '',       // 初始化岗位类型
        IsWork: false,     // 初始化主持工作
        JobRespon: '',     // 初始化工作职责
        Memo: ''           // 初始化备注
      },
      ruleFormQX:{
        UserName:true,
        JobType:true,
        IsWork:true,
        JobRespon:true,
        Memo:true
      },
      userinfo: [],
      UserIDlist:[],
      rules: {
        UserName: [
          { required: true, message: '请输入选择人员', trigger: 'blur' }
        ],
        JobType: [
          { required: true, message: '请选择用户岗位类型', trigger: 'change' }
        ]
      }
    };
  },
  watch: {
    userVisible(val) {
      if (val) {
        
        this.init()

      }
    }
  },
  methods: {
    init() {
      console.log( this.userdj)
      if(this.userdj.length>0){
        for(var i=0;i<this.userdj.length;i++){
               this.UserIDlist.push(this.userdj[i].UserID)
        }
         console.log( this.UserIDlist)
         if(this.title==='编辑人员'){
           this.UserIDlist= this.UserIDlist.filter(item => item !== JSON.parse(JSON.stringify(this.userlist)).UserID);
         }
      }
      const data = {
        Table: [
          {
            Name: "Base_UserInfo",
            Type: "数据库表",
            DbName: "task_demo",
            Filter: {
              Type: "and",
              Filters: [
                {
                  "Type": "cond",
                  "Field": "ROWID",
                  "Operator": "notin",
                  "Value": null,
                  "ValueFun": {
                    "Type": "GetConstValue",
                    "Value": this.UserIDlist
                  }
                }
              ]
            }


          }
        ]
      }
      GetData(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
        if (res.Code === 200) {
          this.userinfo = res.Result.data.Items
          if(this.title==='编辑人员'){
               Object.keys(this.ruleFormQX).forEach(key => {
  this.ruleFormQX[key] = JSON.parse(JSON.stringify(this.userlist)).lingma_sys_params.e.includes(key);
});
            this.ruleForm=JSON.parse(JSON.stringify(this.userlist));
            if(this.ruleForm.IsWork===1 || this.ruleForm.IsWork==='1'){
               this.$set(this.ruleForm, 'IsWork', true)
            }else{
                this.$set(this.ruleForm, 'IsWork', false)
            }
            console.log(this.ruleForm)
          }
        }
      })
    },
    handleUserChange(selectedRowId) {
      const selectedUser = this.userinfo.find(user => user.ROWID === selectedRowId);
      if (selectedUser) {
        this.ruleForm.UserName = selectedUser.UserName;
        this.ruleForm.ROWID = selectedUser.ROWID;
      } else {
        this.ruleForm.UserName = '';
        this.ruleForm.ROWID = '';
      }
    },
    submitForm() {
      this.$refs.rel.validate((valid) => {
        if (valid) {
          if (this.title === '新增人员') {
               this.$set(this.ruleForm, 'createuser', JSON.parse(sessionStorage.getItem('users')).userInfo.ROWID)
            const data = [{
              TableName: 'task_demo@Base_User_DJ',
              CrudModel: {
                Added: [{
                  DJID: this.depjobrow.JobId,
                  JobID: this.depjobrow.JobId,
                  DepID: this.depjobrow.DepID || "",
                  JobType: this.ruleForm.JobType,
                  DepName: this.depjobrow.DepName || "",
                  JobName: this.depjobrow.JobName,
                  Memo: this.ruleForm.Memo,
                  UserID: this.ruleForm.ROWID,
                  UserName: this.ruleForm.UserName,
                  IsWork: this.ruleForm.IsWork ? 1 : 0,
                  JobRespon: this.ruleForm.JobRespon,
                    createuser:this.ruleForm.createuser
            
                }],
                Changed: [],
                Deleted: []
              }
            }]
         BatchTableOperateRequestByCRUD(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
                  if (res.Code === 200) {
                    this.$message.success('新增人员成功');
                    this.$emit('refresh');
                     this.$refs.rel.resetFields();
        
                  } else {
                    this.$message.error('新增人员失败,'+ res.Message);
                  }
                })  
          }else{
            const data = [{
              TableName: 'task_demo@Base_User_DJ',
              CrudModel: {
                Added: [],
                Changed: [{
                  rowid: this.ruleForm.rowid,
                  JobType: this.ruleForm.JobType,
                  Memo: this.ruleForm.Memo,
                  UserID: this.ruleForm.ROWID,
                  UserName: this.ruleForm.UserName,
                  IsWork: this.ruleForm.IsWork ? 1 : 0,
                  JobRespon: this.ruleForm.JobRespon
                }],
                Deleted: []
              }
            }]
            BatchTableOperateRequestByCRUD(data, 'DA242D6EF89B69A7ED5D2728408833AB').then(res => {
                  if (res.Code === 200) {
                    this.$message.success('编辑人员成功');
                    this.$emit('refresh');
                    this.$refs.rel.resetFields();
                  } else {
                    this.$message.error('编辑人员失败,'+ res.Message);
                  }
          })
         }
        } 
      });
    },
    cancelForm() {
      this.$emit('close');
      this.$refs.rel.resetFields();
    }
  }
};
</script>

<style scoped>
.el-dialog__wrapper {
  /* Optional: Adjust dialog wrapper styles if needed */
}

.el-dialog {
  border-radius: 8px;
  /* Example: rounded corners for the dialog */
}

.el-form-item {
  margin-bottom: 20px;
  /* Add some space between form items */
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button+.el-button {
  margin-left: 10px;
}
</style>